package cn.edu.sjtu.se.peakfactory.service.impls;

import java.util.ArrayList;
import java.util.List;
import cn.edu.sjtu.se.peakfactory.dao.bean.Element;
import cn.edu.sjtu.se.peakfactory.dao.bean.UserElement;
import cn.edu.sjtu.se.peakfactory.dao.interfaces.ElementDAO;
import cn.edu.sjtu.se.peakfactory.dao.interfaces.UserElementDAO;
import cn.edu.sjtu.se.peakfactory.service.bean.ElementVB;
import cn.edu.sjtu.se.peakfactory.service.bean.UserElementVB;
import cn.edu.sjtu.se.peakfactory.service.interfaces.ElementService;

public class ElementServiceImpl implements ElementService {
	private ElementDAO elementDAO;
	private UserElementDAO userElementDAO;

	public void setElementDAO(ElementDAO elementDAO) {
		this.elementDAO = elementDAO;
	}

	public void setUserElementDAO(UserElementDAO userElementDAO) {
		this.userElementDAO = userElementDAO;
	}

	@Override
	public UserElementVB getUserElementById(Long userId, Long elementId) {
		UserElement userElement = userElementDAO.getUserElementById(userId, elementId);
		return new UserElementVB(userElement);
	}

	@Override
	public List<UserElementVB> getUserElementByUserId(Long userId) {
		List<UserElement> elements = userElementDAO.getUserElementByUserId(userId);
		List<UserElementVB> result = new ArrayList<UserElementVB>();
		for (UserElement e : elements) {
			result.add(new UserElementVB(e));
		}
		return result;
	}

	@Override
	public void useElementWithAmount(Long userId, Long elementId, int amount) {
		UserElementVB e = this.getUserElementById(userId, elementId);
		if (e != null) {
			Integer count = e.getEleCount();
			if (count != null && count >= amount) {
				count -= amount;
				userElementDAO.updateColumns(e.getId(), new String[] { "eleCount" }, new Object[] { count });
				/*
				 * org.hibernate.Query query =
				 * userElementDAO.getHibernateSession().createQuery(
				 * "update UserElement set eleCount= ? where id=?");
				 * query.setParameter(0, count); query.setParameter(1,
				 * e.getId()); return query.executeUpdate();
				 */
			}
		}
	}

	@Override
	public void addElementWithAmount(Long userId, Long elementId, int amount) {
		UserElementVB e = this.getUserElementById(userId, elementId);
		if (e != null) {
			Integer count = e.getEleCount();
			count = count == null ? amount : (count + amount);
			userElementDAO.updateColumns(e.getId(), new String[] { "eleCount" }, new Object[] { count });
		}
	}

	@Override
	public List<ElementVB> searchElementByName(String elementName) {
		List<Element> elements = elementDAO.searchElementByName(elementName);
		List<ElementVB> result = new ArrayList<ElementVB>();
		for (Element e : elements) {
			result.add(new ElementVB(e));
		}
		return result;
	}
}
